package com.example.proxy.config;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.mitre.dsmiley.httpproxy.RequestBodyEnhanceFilter;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/*
针对post请求做的增强：当表单提交时会丢失参数
 */
public class RequestBodyEnhanceFilterImpl implements RequestBodyEnhanceFilter {
    @Override
    public boolean care(HttpServletRequest request) {

        String s = request.getMethod().toUpperCase();
        String contentType = request.getContentType();
        return s.equals("POST") && (contentType != null && contentType.contains("application/x-www-form-urlencoded"));
    }

    @Override
    public InputStream getExchangeInput(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        while (parameterNames.hasMoreElements()){
            String s = parameterNames.nextElement();
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair(s, request.getParameter(s));
            nameValuePairs.add(basicNameValuePair);
        }

        try {
            //这里的编码不能少
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
            return urlEncodedFormEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
